<?php

namespace App\Http\Controllers\Api;

use App\Models\BackOrder;
use App\Models\Book;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\SellOrder;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use EasyWeChat;

class PaymentController extends Controller
{
    public function wechatNotify()
    {
        // 校验回调参数是否正确
        $data  = app('wechat_pay')->verify();

        $no_first = substr($data->out_trade_no,0,1);
        if($no_first == 'B')
        {
            //卖书的退回订单
            $no = substr($data->out_trade_no,1);
            $order = BackOrder::query()->where('no',$no)->first();
            // 订单不存在则告知微信支付
            if (!$order) {
                return 'fail';
            }
            // 订单已支付
            if ($order->pay_at) {
                // 告知微信支付此订单已处理
                return app('wechat_pay')->success();
            }

            // 将订单标记为已支付
            $order->update([
                'pay_at'     => time(),
                'state'      => 1,
                'pay_no'     => $data->transaction_id,
            ]);

            SellOrder::query()->where('id',$order->sell_order_id)->update(['can_back' => 1]);
        }
        else
        {
            //购买图书订单

            // 找到对应的订单
            $order = Order::query()->where('no', $data->out_trade_no)->first();

            // 订单不存在则告知微信支付
            if (!$order) {
                return 'fail';
            }
            // 订单已支付
            if ($order->pay_at) {
                // 告知微信支付此订单已处理
                return app('wechat_pay')->success();
            }

            // 将订单标记为已支付
            $order->update([
                'pay_at'         => time(),
                'pay_type'       => 2,
                'pay_no'         => $data->transaction_id,
                'state'          => 1,
            ]);

            $items = OrderItem::query()->with(['book'])->where('order_id',$order->id)->get();
            $keyword1 = '';
            foreach ($items as $key=>$item)
            {
                if($key == 0)
                {
                    $keyword1 .= "《".$item->book->title."》";
                }

                if($item['type'] == 1)
                {
                    $item->book->decrement('new_book_stock', 1);
                }
                elseif($item['type'] == 2)
                {
                    $item->book->decrement('good_book_stock', 1);
                }
                elseif($item['type'] == 3)
                {
                    $item->book->decrement('medium_book_stock', 1);
                }
                elseif($item['type'] == 4)
                {
                    $item->book->decrement('medium_book_stock2', 1);
                }
                elseif($item['type'] == 5)
                {
                    $item->book->decrement('medium_book_stock3', 1);
                }
                elseif($item['type'] == 6)
                {
                    $item->book->decrement('medium_book_stock4', 1);
                }
                elseif($item['type'] == 7)
                {
                    $item->book->decrement('medium_book_stock5', 1);
                }
                elseif($item['type'] == 8)
                {
                    $item->book->decrement('medium_book_stock6', 1);
                }

                $item->book->decreaseStock(1);
            }

            $keyword1 .= '...共'.count($items).'本书';

            //发送推送消息
            $user = User::query()->where('id',$order->user_id)->first();

            $officialAccount = EasyWeChat::officialAccount(); // 公众号
            $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
            if(!empty($wechat_user))
            {
                $openid = $wechat_user->openid;

                $first = "您的买书订单支付成功，等待发货\r\n";
                $keyword2 = $order->price.'元';
                $officialAccount->template_message->send([
                    'touser'        => $openid,
                    'template_id'   => '4dSwqWCdFqYu5k00KxoLtX3YTdCeDB2sAbwuyk73irs',
                    'url'  => '',
                    'miniprogram' => [
                        'appid'     => config('wechat.mini_program.default.app_id'),
                        'path'  => '/pages/order/order-detail/order-detail?id='.$order->id,
                    ],
                    'data' => [
                        'first'     => $first,
                        'keyword1'  => $keyword1,
                        'keyword2'  => $keyword2,
                        'keyword3'  => $order->address_receiver,
                        'keyword4'  => $order->address_province_name.$order->address_city_name.$order->address_area_name.$order->address,
                        'keyword5'  => $order->address_mobile."\r\n",
                        'remark'    => '我们将在24小时内为您安排发货，请耐心等待。如收货地址有误，请及时取消订单或联系客服。'
                    ],
                ]);
            }

            /*$sms = app('easysms');
            try {
                $sms->send('15888825922',[
                    'template' => 'SMS_167973962',
                    'data' => [

                    ],
                ]);
            } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getException('aliyun')->getMessage();
                //dd($message);
            }*/
            $officialAccount->template_message->send([
                'touser'        => 'oKOD01EmbGyVy9nEgrq7N6Hh-BG0',
                'template_id'   => 'T2LwyJ_zHil6B0QfKDKfjUL19358TPQlVVoJ6reMMrU',
                'url'  => '',
                'miniprogram' => [
                    'appid'     => config('wechat.mini_program.default.app_id'),
                    'path'  => '',
                ],
                'data' => [
                    'first'     => '后台有新的购书订单,请尽快发货'."\r\n",
                    'keyword1'  => $order->no,
                    'keyword2'  => '快鱼二手书',
                    'keyword3'  => date('Y-m-d H:i:s',$order->created_at)."\r\n",
                    'remark'    => ''
                ],
            ]);
        }

        return app('wechat_pay')->success();
    }

    public function wechatRefundNotify(Request $request)
    {
        // 给微信的失败响应
        $failXml = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>';
        $data = app('wechat_pay')->verify(null, true);

        // 没有找到对应的订单，原则上不可能发生，保证代码健壮性
        $order = Order::where('no', $data['out_trade_no'])->first();
        if(!$order) {
            return $failXml;
        }

        if ($data['refund_status'] === 'SUCCESS') {
            // 退款成功，将订单退款状态改成退款成功
            $order->update([
                'refund_status' => 2,
                'cancel_at'     => time(),
                'state'         => -1,
                'updated_at'    => time(),
            ]);

            $item = OrderItem::query()->with(['book'])->where('order_id',$order->id)->orderBy('id','asc')->first();
            $keyword2 = "《".$item->book->title."》...共".$order->amount.'本书';

            $user = \DB::table('users')->select(['unionid','id'])->where('id',$order->user_id)->first();
            $officialAccount = EasyWeChat::officialAccount(); // 公众号
            $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
            if(!empty($wechat_user))
            {
                $openid = $wechat_user->openid;

                $first = "您的买书订单取消成功，已退款\r\n";
                $officialAccount->template_message->send([
                    'touser'        => $openid,
                    'template_id'   => 'eAewZ_8ibUx3OjnQdL2WJQTXIAPC5mgMQn7iS9QXlRg',
                    'url'  => '',
                    'miniprogram' => [
                        'appid'     => config('wechat.mini_program.default.app_id'),
                        'path'  => '/pages/order/order-detail/order-detail?id='.$order->id,
                    ],
                    'data' => [
                        'first'     => $first,
                        'keyword1'  => $order->price.'元',
                        'keyword2'  => $keyword2,
                        'keyword3'  => $order->no."\r\n",
                        'remark'    => '退款将原路退回到您的支付账户，请注意查收。（微信支付退款到账时间，请以微信通知为准）'
                    ],
                ]);
            }

            $items = OrderItem::query()->select(['book_id','order_id','type'])->where('order_id',$order->id)->get();
            foreach ($items as $v)
            {
                $book = Book::find($v->book_id);
                if($v->type == 1)
                {
                    $book->increment('new_book_stock', 1);
                }
                elseif($v->type == 2)
                {
                    $book->increment('good_book_stock', 1);
                }
                elseif($v->type == 3)
                {
                    $book->increment('medium_book_stock', 1);
                }
                elseif($v->type == 4)
                {
                    $book->increment('medium_book_stock2', 1);
                }
                elseif($v->type == 5)
                {
                    $book->increment('medium_book_stock3', 1);
                }
                elseif($v->type == 6)
                {
                    $book->increment('medium_book_stock4', 1);
                }
                elseif($v->type == 7)
                {
                    $book->increment('medium_book_stock5', 1);
                }
                elseif($v->type == 8)
                {
                    $book->increment('medium_book_stock6', 1);
                }

                //加总库存
                $book->addStock(1);
            }

        } else {
            // 退款失败，将具体状态存入 extra 字段，并表退款状态改成失败
            $order->update([
                'refund_status'      => -1,
                'refund_failed_code' => $data['refund_status']
            ]);
        }

        return app('wechat_pay')->success();
    }
}
